package org.aliwo.syn;

/**
 * 死锁案例
 */
public class DeadLock {
    public static String locka = "a";

    public static String lockb = "b";

    public void methodA() {
        synchronized (locka) {
            System.out.println("线程:" + Thread.currentThread().getName() + "获取到锁a");

            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            synchronized (lockb) {
                System.out.println("线程:" + Thread.currentThread().getName() + "获取到锁b");
            }

        }
    }

    public void methodB() {
        synchronized (lockb) {
            System.out.println("线程:" + Thread.currentThread().getName() + "获取到锁b");

            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            synchronized (locka) {
                System.out.println("线程:" + Thread.currentThread().getName() + "获取到锁a");
            }
        }
    }

    public static void main(String[] args) {
        System.out.println("主线程:" + Thread.currentThread().getName() + "开始执行");
        DeadLock deadLock = new DeadLock();
        new Thread(()-> deadLock.methodA()).start();
        new Thread(()-> deadLock.methodB()).start();
        System.out.println("主线程:" + Thread.currentThread().getName() + "执行结束");
    }
}
